<template>
  <div class="page-container">
    <!-- 表单部分 -->
    <div class="form-section">
      <div class="header">
        <button @click="goBack">返回</button>
        <h1>编辑 Request {{ request.Req_id }}</h1>
      </div>
      
      <form @submit.prevent="showConfirmationDialog" class="form-grid1">
        <div class="form-grid">
          <div class="form-group">
            <label for="req_id">Request ID:</label>
            <input 
              type="text" 
              v-model="request.Req_id"
              required 
              disabled
            />
          </div>
          <div class="form-group">
            <label for="item">Item:</label>
            <input type="text" v-model="request.Item" />
          </div>
          <div class="form-group">
            <label for="priority">Priority:</label>
            <select v-model="request.Priority" required>
              <option value="" disabled>Select Priority</option>
              <option value="1 - Critical">1 - Critical</option>
              <option value="2 - High">2 - High</option>
              <option value="3 - Moderate">3 - Moderate</option>
              <option value="4 - Low">4 - Low</option>
            </select>
          </div>
          <div class="form-group">
            <label for="opened">Opened:</label>
            <input 
              type="datetime-local" 
              v-model="request.Opened"
              required 
            />
          </div>
          <div class="form-group">
            <label for="opened_by">Opened By:</label>
            <input type="text" v-model="request.Opened_by" required />
          </div>
          <div class="form-group">
            <label for="state">State:</label>
            <select v-model="request.State" required>
              <option value="" disabled>Select State</option>
              <option value="Open">Open</option>
              <option value="Closed Complete">Closed Complete</option>
              <option value="Closed Incomplete">Closed Incomplete</option>
              <option value="Closed Skipped">Closed Skipped</option>
            </select>
          </div>
          <div class="form-group">
            <label for="short_description">Short Description:</label>
            <input type="text" v-model="request.Short_description" required />
          </div>
          <div class="form-group">
            <label for="description">Description:</label>
            <textarea v-model="request.Description"></textarea>
          </div>
          <div class="form-group">
            <label for="assigned_to">Assigned To:</label>
            <input type="text" v-model="request.Assigned_to" />
          </div>
          <div class="form-group">
            <label for="assignment_group">Assignment Group:</label>
            <select v-model="request.Assignment_group" required>
              <option value="" disabled>Select Assignment Group</option>
              <option value="Cloud-Administrators-L1">Cloud-Administrators-L1</option>
              <option value="Cloud-Administrators-L2">Cloud-Administrators-L2</option>
              <option value="Cloud-Administrators-Tech Lead">Cloud-Administrators-Tech Lead</option>
              <option value="">None</option>
            </select>
          </div>
          <div class="form-group">
            <label for="project">Project:</label>
            <input type="text" v-model="request.Project" />
          </div>
        </div>
        <button type="submit">更新 Request</button>
      </form>
      
      <!-- 确认对话框 -->
      <ConfirmationDialog2
        v-if="showDialog"
        @confirm="updateRequest"
        @cancel="showDialog = false"
      />
    </div>
    
    <!-- 评论区部分 -->
    <div class="comments-section">
      <h2>评论区</h2>
      
      <!-- 添加新评论 -->
      <div v-if="isLoggedIn" class="comment-form">
        <textarea 
          v-model="newComment" 
          placeholder="请输入您的评论..."
          rows="3"
        ></textarea>
        <button @click="addComment" :disabled="isLoading">
          {{ isLoading ? '提交中...' : '提交评论' }}
        </button>
      </div>
      <div v-else class="login-prompt">
        <p>请先登录后再发表评论</p>
        <router-link to="/login" class="login-link">
          点击这里登录
        </router-link>
      </div>
      
      <!-- 评论列表 -->
      <div class="comments-list">
        <div v-for="comment in comments" :key="comment.id" class="comment">
          <div class="comment-header">
            <span class="username">{{ comment.username }}</span>
            <span class="role-badge" :class="comment.admin_id ? 'admin' : 'user'">
              {{ comment.admin_id ? '管理员' : '用户' }}
            </span>
            <span class="time">{{ formatCommentDate(comment.created_at) }}</span>
          </div>
          <div class="comment-content">
            {{ comment.comment }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import ConfirmationDialog2 from '../components/ConfirmationDialog2.vue';

export default {
  name: 'RequestDetail',
  
  components: {
    ConfirmationDialog2
  },
  
  data() {
    return {
      request: {
        id: '',
        Req_id: '',
        Item: '',
        Priority: '',
        Opened: '',
        Opened_by: '',
        State: '',
        Short_description: '',
        Description: '',
        Assigned_to: '',
        Assignment_group: '',
        Project: ''
      },
      showDialog: false,
      comments: [],
      newComment: '',
      currentUser: {
        username: localStorage.getItem('username'),
        role: localStorage.getItem('userRole')
      },
      isLoading: false, // 加载状态
    };
  },
  
  computed: {
    isLoggedIn() {
      return !!(this.currentUser.username && this.currentUser.role);
    }
  },
  
  async mounted() {
    await this.fetchRequest();
    await this.fetchComments();
  },
  
  methods: {
    async fetchRequest() {
      const reqId = this.$route.params.reqId;
      try {
        const response = await axios.get(`http://localhost:3000/api/requests/${reqId}`);
        this.request = response.data;
        
        // 格式化日期，将 UTC 时间加上8小时
        if (this.request.Opened) {
          this.request.Opened = this.addHours(this.request.Opened, 8).toISOString().slice(0, 16);
        }
      } catch (error) {
        console.error('获取请求详情失败:', error);
        alert('获取请求详情失败: ' + error.message);
      }
    },
    
    addHours(dateString, hours) {
      const date = new Date(dateString);
      date.setHours(date.getHours() + hours);
      return date;
    },
    
    async fetchComments() {
      try {
        const response = await axios.get(`http://localhost:3000/api/requests/${this.$route.params.reqId}/comments`);
        this.comments = response.data;
      } catch (error) {
        console.error('获取评论失败:', error);
      }
    },
    
    async addComment() {
      if (!this.newComment.trim() || !this.isLoggedIn) {
        alert('请先登录后再发表评论');
        return;
      }

      this.isLoading = true; // 显示加载状态

      try {
        let nickname = this.currentUser.username; // 默认使用用户名

        // 尝试获取昵称
        try {
          const nicknameResponse = await axios.post('http://localhost:3000/api/getNickname', {
            username: this.currentUser.username,
            userRole: this.currentUser.role,
          });

          if (nicknameResponse.data.nickname) {
            nickname = nicknameResponse.data.nickname;
          }
        } catch (nicknameError) {
          console.error('获取昵称失败，使用用户名作为默认值:', nicknameError);
        }

        // 拼接评论内容
        const commentWithSignature = `${this.newComment} ——由${nickname}创建`;

        // 提交评论
        const response = await axios.post(
          `http://localhost:3000/api/requests/${this.$route.params.reqId}/comments`,
          {
            comment: commentWithSignature, // 提交拼接后的评论内容
            username: this.currentUser.username,
            userRole: this.currentUser.role,
          }
        );

        console.log('Comment response:', response.data);

        // 清空输入框并刷新评论列表
        this.newComment = '';
        await this.fetchComments();
      } catch (error) {
        console.error('添加评论失败:', error);
        alert('添加评论失败: ' + (error.response?.data?.details || error.message));
      } finally {
        this.isLoading = false; // 隐藏加载状态
      }
    },
    
    formatCommentDate(dateString) {
      return new Date(dateString).toLocaleString();
    },
    
    showConfirmationDialog() {
      this.showDialog = true;
    },
    
    async updateRequest() {
      try {
        const formattedRequest = {
          ...this.request,
          Opened: this.request.Opened ? new Date(this.request.Opened).toISOString() : null
        };
        
        await axios.put(`http://localhost:3000/api/requests/${this.request.Req_id}`, formattedRequest);
        alert('Request 更新成功');
        this.$router.push({ name: 'RequestOverview' });
      } catch (error) {
        console.error('更新 Request 失败:', error);
        alert('更新 Request 失败: ' + (error.response?.data?.message || error.message));
      } finally {
        this.showDialog = false;
      }
    },
    
    goBack() {
      this.$router.push({ name: 'RequestOverview' });
    }
  }
};
</script>

<style scoped>
.page-container {
  width: 750px;
  padding: 10px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
  flex-direction: column;
  height: 950px;
  margin-bottom: 100px;
  background-color: white; /* 白色背景 */
  border-radius: 10px; /* 圆角 */
  padding: 10px; /* 内边距 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加阴影 */
}

.form-section {
  flex: 1;
}

.header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  background-color: white;
  padding: 10px 0;
}

.header button {
  background-color: #007bff; /* 设置背景颜色为蓝色 */
  color: white; /* 设置文字颜色为白色 */
  border: none; /* 去掉边框 */
  border-radius: 5px; /* 添加圆角 */
  cursor: pointer; /* 鼠标悬停时显示手型 */
  transition: background-color 0.3s; /* 添加过渡效果 */
}

.header button:hover {
  background-color: #0056b3; /* 悬停时背景颜色变为深蓝色 */
}

.header h1 {
  margin: 0;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  margin-bottom: 20px;
  padding: 0 10px;
}
.form-grid1 button {
  background-color: #007bff; /* 设置背景颜色为蓝色 */
  color: white; /* 设置文字颜色为白色 */
  border: none; /* 去掉边框 */
  border-radius: 5px; /* 添加圆角 */
  cursor: pointer; /* 鼠标悬停时显示手型 */
  transition: background-color 0.3s; /* 添加过渡效果 */
}

.form-grid1 button:hover {
  background-color: #0056b3; /* 悬停时背景颜色变为深蓝色 */
}

.form-group {
  margin-bottom: 8px;
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 3px;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-group:nth-last-child(2),
.form-group:last-child {
  grid-column: 1 / -1;
}

textarea {
  height: 60px;
  resize: vertical;
}

button {
  padding: 8px 16px;
  margin-right: 10px;
}

.comments-section {
  background-color: #f5f5f5;
  padding: 20px;
  border-radius: 4px;
  margin-top: 20px;
}

.comment-form {
  margin-bottom: 20px;
}

.comment-form textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 10px;
  resize: vertical;
}

.comment-form button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.comment-form button:hover {
  background-color: #45a049;
}

.comments-list {
  margin-top: 20px;
}

.comment {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 0.9em;
}

.username {
  font-weight: bold;
}

.role-badge {
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
  margin: 0 8px;
}

.role-badge.admin {
  background-color: #dc3545;
  color: white;
}

.role-badge.user {
  background-color: #28a745;
  color: white;
}

.time {
  color: #666;
  margin-left: auto;
}

.comment-content {
  white-space: pre-wrap;
}

.login-prompt {
  text-align: center;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
  color: #666;
}

.login-link {
  display: inline-block;
  margin-top: 10px;
  color: #007bff;
  text-decoration: none;
}

.login-link:hover {
  text-decoration: underline;
}

.page-container::-webkit-scrollbar {
  width: 8px;
}

.page-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.page-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.page-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>